package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.PageComDto;
import com.itheima.mapper.SubjectsMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Subjects;
import com.itheima.service.SubjectsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
*
*/
@Service
public class SubjectsServiceImpl extends ServiceImpl<SubjectsMapper, Subjects>
implements SubjectsService {

    @Autowired
    private SubjectsMapper subjectsMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageComDto findPage(Integer page, Integer pagesize, String subjectName) {
        IPage<Subjects> p = new Page<>(page,pagesize);
        LambdaQueryWrapper<Subjects> wrapper = new LambdaQueryWrapper<>();
        if(subjectName != null){
            wrapper.like(Subjects::getSubjectName,subjectName);
        }
        IPage<Subjects> subjectsIPage = subjectsMapper.selectPage(p, wrapper);
        List<Subjects> records = subjectsIPage.getRecords();
        for (Subjects record : records) {
            record.setUsername(userMapper.selectById(record.getCreatorID()).getUsername());
        }
        PageComDto<Subjects> subjectsPageComDto = new PageComDto<>();
        subjectsPageComDto.setPageSize((int) subjectsIPage.getSize());
        subjectsPageComDto.setPage((int) subjectsIPage.getCurrent());
        subjectsPageComDto.setItems(records);
        subjectsPageComDto.setPages((int) subjectsIPage.getPages());
        subjectsPageComDto.setCounts((int) subjectsIPage.getTotal());
        return subjectsPageComDto;
    }
}
